package edu.cn.nlsde.tmfst.crawler.processor;

import edu.cn.nlsde.Utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

public class PictureDownloader {
    static Logger mylog = LoggerFactory.getLogger(PictureDownloader.class.getName());

    public static String downImgs(String imgsrc) {


        String filePath = "userImages/" + Utils.Date2String(new Date(), "yyyy-MM-dd") + "/";
        String fileRealPath = "";
        //获取图片
        try {
            //创建目录
            File files = new File(filePath);
            if (!files.exists()) {
                files.mkdirs();
            }
            URL url = new URL(imgsrc);
            //连接网络图片地址
            HttpURLConnection uc = (HttpURLConnection) url.openConnection();
            //获取连接的输入流
            InputStream is = uc.getInputStream();

            //截取文件名
            //String filename=imgsrc.substring(imgsrc.lastIndexOf("/"));

            //创建文件
            File file = new File(filePath + imgsrc.substring(imgsrc.lastIndexOf("/")));
            //输入到本地
            FileOutputStream fos = new FileOutputStream(file);
            int line = -1;
            while ((line = is.read()) != -1) {
                fos.write(line);
            }
            is.close();
            fos.close();

            fileRealPath = file.getPath();

        } catch (Exception e) {
            mylog.error("download picture error", e);
        }

        return fileRealPath;

    }

}

